<?php
require_once __DIR__ . '/../models/Category.php';

class CategoryController
{
	private $db;
	private $categoryModel;

	public function __construct($db)
	{
		$this->db = $db;
		$this->categoryModel = new Category($db);
	}

	/**
	 * 统一分类响应方法
	 */
	private function sendCategoryResponse($data, $type)
	{
		header('Content-Type: application/json');

		if (empty($data)) {
			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'type' => $type,
				'count' => 0,
				'data' => []
			], JSON_UNESCAPED_UNICODE);
			return;
		}

		http_response_code(200);
		echo json_encode([
			'status' => 'success',
			'type' => $type,
			'count' => count($data),
			'data' => $data
		], JSON_UNESCAPED_UNICODE);
	}

	/**
	 * 获取帖子分类
	 */
	public function getPostCategories()
	{
		try {
			$categories = $this->categoryModel->getPostCategories();
			$this->sendCategoryResponse($categories, 'post');
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 获取话题分类
	 */
	public function getTopicsCategories()
	{
		try {
			$categories = $this->categoryModel->getTopicsCategories();
			$this->sendCategoryResponse($categories, 'topic');
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 统一错误处理
	 */
	private function handleError($e)
	{
		error_log("[Category Controller] 错误: " . $e->getMessage());
		http_response_code(500);
		echo json_encode([
			'status' => 'error',
			'message' => $e->getMessage()
		], JSON_UNESCAPED_UNICODE);
	}
}
?>